package com.zyk.plugin.costtime;

import com.zyk.plugin.JaTransformer;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.ClassFileLocator;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.pool.TypePool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.ProtectionDomain;

import static net.bytebuddy.matcher.ElementMatchers.*;

public class CostTimeTransformer implements JaTransformer {
    private static final Logger LOGGER = LoggerFactory.getLogger(CostTimeTransformer.class);

    @Override
    public String getHookPackageName() {
        return "com.example";
    }

    @Override
    public byte[] loadClass(ClassLoader loader, String className,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) {
        byte[] ans = null;
        try {
            ClassFileLocator classLocator = ClassFileLocator.ForClassLoader.of(loader);

            DynamicType.Unloaded<?> make = new ByteBuddy()
                    .redefine(TypePool.Default.of(classLocator).describe(className).resolve(),classLocator)
                    .visit(Advice.to(CostTimeAdvice.class)
                            .on(any().and(not(isConstructor())))
                    )
                    .make();
            ans = make.getBytes();
            make.close();
            classLocator.close();
        } catch (Exception e) {
            LOGGER.error("{} 转换失败", className, e);
            return null;
        }
        return ans;
    }
}